package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.JsonResult;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/userlogin")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session) {
        try {
            Employee employee = employeeService.login(username, password);
            //登陆通过(登陆的逻辑判断放到业务层处理)，存储用户信息到session中
            //session.setAttribute("USER_IN_SESSION", employee);
            //使用自定义的工具类UserContext
            UserContext.setCurrentUser(employee);
            //登陆时存入权限信息
            List<String> stringList = permissionService.selectByEmpId(employee.getId());
            //session.setAttribute("PERMISSION_IN_SESSION",stringList);
            UserContext.setPermission(stringList);
            return new JsonResult();
        }catch (Exception e){
            return new JsonResult(false,e.getMessage());
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
            request.getSession().invalidate();
            return "redirect:/login.html";
    }

}
